<template>
  <div id="loader" class="lds-dual-ring centered">
    <a-modal v-model:visible="visible" title="自由探索阶段" @ok="handleOk">
      <template #footer>
        <a-button key="submit" type="primary" @click="handleOk">开始自由游览</a-button>
      </template>
      <p>接下来，我们将正式开始实验。你将有6分钟时间自由、充分地浏览迷宫，
        寻找迷宫中的5个物品（热气球、火堆、茶杯、蜡烛、树）。请努力记住它们的位置，并且记住你的寻找路线。
        迷宫墙壁上的画可以帮助你记忆。
      </p>
      <p>行走按键：W（向前）、S（向后）、A（向左）、D（向右）</p>
      <p>转向：鼠标滑动</p>
      <p>请点击“开始”按钮后,再次单击鼠标左键开始实验。</p>
    </a-modal>
    <a-modal v-model:visible="visible2" title="测试阶段" @ok="handleOk2">
      <template #footer>
        <a-button key="submit" type="primary" @click="handleOk2">开始</a-button>
      </template>
      <p>此阶段为测试环节，请您在90秒内尽快找到{{ nameList[level] }}，并且与目标发生碰撞，即可完成本轮任务。
      </p>
      <p>行走按键：W（向前）、S（向后）、A（向左）、D（向右）</p>
      <p>转向：鼠标滑动</p>
      <p>请先按'ESC'显示光标后再鼠标点击'开始'按钮开始测试。</p>
    </a-modal>
  </div>
  <div class="scene">
    <a-scene style="display: none;">
      <!-- Assets -->
      <a-assets>
        <img id="pavement" src="@/assets/test3/pavement.jpg" alt="pavement"/>
        <!--        <img id="ball" src="@/assets/test3/ball.jpg" alt="ball"/>-->
        <img id="red-carpet" src="@/assets/test3/red-carpet.jpg" alt="red-carpet"/>
        <img id="pic1" src="@/assets/test3/pic1.jpeg" alt="pic1"/>
        <img id="pic2" src="@/assets/test3/pic2.jpeg" alt="pic2"/>
        <img id="pic3" src="@/assets/test3/pic3.jpg" alt="pic3"/>
        <img id="pic4" src="@/assets/test3/pic4.jpeg" alt="pic4"/>
        <img id="brick-01" src="@/assets/test3/361677506372_.pic.jpg" alt="pic4"/>

        <a-asset-item id="f-obj"
                      src="http://qiniu.bodamedical.xyz/xxr/3D%20Air%20Balloon%20Illustration.obj"></a-asset-item>
        <a-asset-item id="f-mtl"
                      src="http://qiniu.bodamedical.xyz/xxr/3D%20Air%20Balloon%20Illustration.mtl"></a-asset-item>

        <a-asset-item id="d-obj" src="http://qiniu.bodamedical.xyz/xxr/3D Bonfire Illustration.obj"></a-asset-item>
        <a-asset-item id="d-mtl" src="http://qiniu.bodamedical.xyz/xxr/3D Bonfire Illustration.mtl"></a-asset-item>

        <a-asset-item id="m-obj" src="http://qiniu.bodamedical.xyz/xxr/Tea.obj"></a-asset-item>
        <a-asset-item id="m-mtl" src="http://qiniu.bodamedical.xyz/xxr/Tea.mtl"></a-asset-item>
        <a-asset-item id="s-obj" src="http://qiniu.bodamedical.xyz/xxr/Candle.obj"></a-asset-item>
        <a-asset-item id="s-mtl" src="http://qiniu.bodamedical.xyz/xxr/Candle.mtl"></a-asset-item>

        <a-asset-item id="l-obj" src="http://qiniu.bodamedical.xyz/xxr/Tree.obj"></a-asset-item>
        <a-asset-item id="l-mtl" src="http://qiniu.bodamedical.xyz/xxr/Tree.mtl"></a-asset-item>
      </a-assets>

      <!-- Environment -->
      <a-sky height="2048" color="#111" width="2048"></a-sky>
      <a-light type="ambient" color="#fff" intensity="0.8"></a-light>

      <a-plane material="src: #pavement; repeat: 50 50" static-body rotation="-90 0 0" height="100"
               width="100"></a-plane>

      <a-entity id="f" position="-8 0.5 22" scale="1 1 1" static-body rotation="-20 0 0"
                obj-model="obj: #f-obj; mtl: #f-mtl"></a-entity>
      <a-entity id="d" position="24 0.5 -14" scale="1 1 1" static-body rotation="-20 0 0"
                obj-model="obj: #d-obj; mtl: #d-mtl"></a-entity>
      <a-entity id="m" position="9 0.5 -9" scale="1 1 1" static-body rotation="-20 0 0"
                obj-model="obj: #m-obj; mtl: #m-mtl"></a-entity>
      <a-entity id="s" position="9 0.5 -20" scale="1 1 1" static-body rotation="-20 0 0"
                obj-model="obj: #s-obj; mtl: #s-mtl"></a-entity>
      <a-entity id="l" position="0 0.5 0" scale="1 1 1" static-body rotation="-20 0 0"
                obj-model="obj: #l-obj; mtl: #l-mtl"></a-entity>

      <!-- Player -->
      <a-entity id="player" position="10 1.5 10" camera="user-height: 1.7" universal-controls kinematic-body listener
                player>
      </a-entity>

      <!-- Maze -->
      <a-entity id="maze" mazify></a-entity>
    </a-scene>
  </div>


  <div class="clock" v-show="showTimer">
    <vue-countdown ref="count" :time="timer" :auto-start="false"  @end="onCountdownEnd" v-slot="{ totalSeconds }">
      还剩：{{ totalSeconds }} 秒
    </vue-countdown>
  </div>

</template>

<script>
import {useRouter} from "vue-router";
import {ref,getCurrentInstance, onMounted} from "vue";
import {mazify} from "@/app/test3/component/mazify";
import {checkAnswer, postAnswer} from "@/utils/api";
import {message} from 'ant-design-vue';
import VueCountdown from '@chenfengyuan/vue-countdown';
export default ({
  components: {
    VueCountdown
  },
  setup() {
    const timer = ref(300 * 1000);
    const mode = ref(1);
    const showTimer = ref(false);
    const level = ref(0);
    const idList = ref(["#f", "#d", "#m", "#s", "#l"]);
    const nameList = ref(["热气球", "火堆", "茶杯", "蜡烛", "树"]);
    const obList = ref([{x: -7, y: 0.5, z: 22}, {x: 23, y: 0.5, z: -14}, {x: 8, y: 0.5, z: -9}, {
      x: 7,
      y: 0.5,
      z: -20
    }, {x: 0, y: 0.5, z: 20}]);
    let currentInstance = ''

    onMounted(() => {
      currentInstance = getCurrentInstance();
      let Entity = document.querySelector('#maze').components
      if (Entity.mazify) {
        return
      }
      mazify();
    })

    const nextTest = (flag) => {
      const t = currentInstance.ctx.$refs.count.totalSeconds;
      postAnswer([{"token": "", "answer": flag, "delta": 90 - t}], "test3", level.value)
      level.value++;
      if (level.value === 5) {
        // end原先跳回结束页面
        router.push("/R")
      }
      showTimer.value = false;
      visible2.value = true;
    };
    // 开始
    const benginTimer = () => {
      showTimer.value = true;
      currentInstance.ctx.$refs.count.restart();
    };

    const visible = ref(true);
    const visible2 = ref(false);
    const router = useRouter();
    const showModal = () => {
      visible.value = true;
    };

    const handleOk = () => {
      visible.value = false;
      timer.value = 300 * 1000;
      benginTimer();
    };
    const handleOk2 = () => {
      visible2.value = false;
      let player = document.querySelector("#player");
      player.setAttribute('position', "10 1.5 10")
      timer.value = 90 * 1000;
      mode.value = 2;
      const target = document.querySelector(idList.value[level.value]);
      const collide = (evt) => {
        if (evt.detail.body.el.id !== undefined && evt.detail.body.el.id === "player") {
          nextTest("1");
          // 找到目标物
          message.success("恭喜你找到了目标物，本轮结束。")
          target.removeEventListener('collide', collide)
        }
      };
      target.addEventListener('collide', collide);
      benginTimer();
    };
    const goOn = () => {
      router.push("/test3/round");
    };
    // 倒计时结束
    const onCountdownEnd = () => {
      if (mode.value===1){
        message.success("时间到，接下来进入测试阶段")
      }
      if (mode.value===2){
        nextTest("0")
        message.success("很遗憾你没有找到目标，本轮结束")
      }
      visible2.value = true;
      showTimer.value = false;
    };
    return {
      onCountdownEnd,
      currentInstance,
      timer,
      showTimer,
      level,
      visible,
      visible2,
      handleOk,
      handleOk2,
      goOn,
      nextTest,
      obList,
      idList,
      nameList,
      showModal,
    };
  },
  beforeCreate() {
    document.onkeydown = undefined;
    const router = useRouter();
    checkAnswer("test3", 5).then(res => {
      if (res.data.checked === 1) {
        router.push("/R")
      }
    })
  },
  // onMounted() {
  //   // 检查组件是否被注册，如果注册则返回
  //   let Entity = document.querySelector('#maze').components
  //   if (Entity.mazify) {
  //     return
  //   }
  //   mazify();
  // },
});

</script>

<style scoped>

.clock {
  width: 250px;
  height: 40px;
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  padding: 30px; /* Location of the box */
  float: left;
  font-size: large;
  color: #42aaee;
}

.lds-dual-ring {
  display: inline-block;
  width: 80px;
  height: 80px;
}

.lds-dual-ring:after {
  content: " ";
  display: block;
  width: 64px;
  height: 64px;
  border-radius: 50%;
  animation: lds-dual-ring 1.2s linear infinite;
}

@keyframes lds-dual-ring {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.centered {
  position: fixed; /* or absolute */
  top: calc(50% - 64px);
  left: calc(50% - 64px);
}

/* Add Animation */
@-webkit-keyframes animatetop {
  from {
    top: -300px;
    opacity: 0;
  }
  to {
    top: 0;
    opacity: 1;
  }
}

@keyframes animatetop {
  from {
    top: -300px;
    opacity: 0;
  }
  to {
    top: 0;
    opacity: 1;
  }
}

</style>
